<?php

namespace app\merchant\controller\apps\sharing;

use app\merchant\controller\Base;
use app\merchant\model\sharing\Category as CategoryModel;

/**
 * 拼团商品分类
 * Class Category
 * @package app\merchant\controller\apps\sharing
 */
class Category extends Base
{
    /**
     * 商品分类列表
     * @return mixed
     */
    public function index()
    {
        $model = new CategoryModel;
        $list = $model->getCacheTree();
        return $this->renderSuccess($list,'查询成功');
    }

    /**
     * 商品分类详情
     * @return mixed
     */
    public function detail()
    {
        $param = $this->postData();
        if(!isset($param['category_id']) || isInt($param['category_id'])){
            return $this->renderError([],"参数错误");
        }
        $model = CategoryModel::detail($param['category_id']);
        if(!$model){
            return $this->renderError([],"分类不存在，请刷新重试");
        }

        return $this->renderSuccess($model,'查询成功');
    }

    /**
     * 添加商品分类
     * @return array|mixed
     */
    public function add()
    {
        $model = new CategoryModel;
        // 新增记录
        if ($model->add($this->postData())) {
            return $this->renderSuccess([],'添加成功');
        }
        return $this->renderError([],$model->getError() ?: '添加失败');
    }

    /**
     * 编辑商品分类
     * @param $category_id
     * @return array|mixed
     * @throws \think\exception\DbException
     */
    public function edit()
    {
        $param = $this->postData();
        if(!isset($param['category_id']) || isInt($param['category_id'])){
            return $this->renderError([],"参数错误");
        }
        $model = CategoryModel::detail($param['category_id']);
        if(!$model){
            return $this->renderError([],"分类不存在，请刷新重试");
        }
        // 更新记录
        if ($model->edit($param)) {
            return $this->renderSuccess([],'编辑成功');
        }
        return $this->renderError([],$model->getError() ?: '编辑失败');
    }

    /**
     * 删除商品分类
     * @param $category_id
     * @return array
     * @throws \think\exception\DbException
     */
    public function delete()
    {
        $param = $this->postData();
        if(!isset($param['category_id']) || isInt($param['category_id'])){
            return $this->renderError([],"参数错误");
        }
        $model = CategoryModel::detail($param['category_id']);
        if(!$model){
            return $this->renderError([],"分类不存在，请刷新重试");
        }

        if (!$model->remove($param['category_id'])) {
            return $this->renderError([],$model->getError() ?: '删除失败');
        }
        return $this->renderSuccess([],'删除成功');
    }

}
